# -*- coding: utf-8 -*-
"""
yanzg
"""
from django.utils import timezone
import jwt
from jwt import exceptions as jwt_exceptions
import datetime
from django.conf import settings

from blueapps.utils.fancy_dict import FancyDict
from blueapps.utils.logger import logger

class SopsJwtHandler(object):
    def __init__(self, request):
        self.request = request

        self.raw_content = request.META.get("HTTP_AUTHORIZATION", "")
        self.username = request.user.username


        self.error_message = ""
        self.is_valid = False

        self.payload = {}
        self.headers = {}
        #self.get_jwt_info()

        self.user = self.get_username()

    def get_username(self):
        return FancyDict(self.payload.get("username", {}))

    def get_jwt_info(self):
        # raw_content内容http请求头元参数,   Authorization:Token Aax23BxCsIDbsE
        logger.debug("http请求头认证内容原始内容  %s" % self.raw_content)
        if not self.raw_content:
            self.error_message = "Authorization not in http header or it is empty,无法get到http请求头中的auth元数据"
            return False

        type, credentials = self.raw_content.split(' ') # 空格分隔获取token串

        if not type.lower() == 'token':
            self.error_message = "Authorization type not support,http请求头auth元数据未找到token类型"
            return False

        if not credentials:
            self.error_message = "Authorization credentials is empty,http请求头auth元数据未找到token串"
            return False

        try:
            # 解密
            self.payload = jwt.decode(
                credentials, settings.SOPS_TOKEN_SECRET_KEY,  algorithms='HS256'
            )

            self.is_valid = True
        except jwt_exceptions.InvalidKeyError:
            self.error_message = "SOPS_TOKEN_SECRET_KEY error,认证公共key错误"
        except jwt_exceptions.DecodeError:
            self.error_message = "Invalid SOPS_JWT, wrong format or value,token认证失败"
        except jwt_exceptions.ExpiredSignatureError:
            self.error_message = "Invalid SOPS_JWT, which is expired,token已过期"
        except jwt_exceptions.InvalidTokenError:
            self.error_message = "Invalid SOPS_JWT, which is not valid Token,token非法"
        except Exception as error:
            self.error_message = error.message

        if self.error_message:
            logger.exception(
                "[sops_jwt] decode jwt fail, err: %s" % self.error_message
            )

    def generate_jwt_token(self):
        '''
        yanzg
        '''
        payload = {
            'exp': timezone.now() + datetime.timedelta(minutes=3),  # 过期时间
            'iat': timezone.now(),  # 签发时间
            'data': {'username': self.username}  # 自定义数据
        }
        # 密钥串
        secret = settings.SOPS_TOKEN_SECRET_KEY  # 加解密密钥
        algorithm = 'HS256'
        token = jwt.encode(payload, secret, algorithm)
        return token


